package com.example.weather_forecast;

import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseWeatherFragment extends Fragment {

    private static final String TAG = "BaseWeatherFragment";
    private static final int MAX_RETRY_COUNT = 3;
    private int retryCount = 0;

    // UI 组件
    protected RecyclerView recyclerView;
    protected ProgressBar progressBar;
    protected TextView errorTextView;
    protected View loadingLayout;
    protected View errorLayout;
    protected View emptyLayout;
    protected Button retryButton;

    // 数据适配器
    protected WeatherAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        // 动态选择布局（根据子类类型）
        int layoutRes = getFragmentLayoutRes();
        View rootView = inflater.inflate(layoutRes, container, false);

        initViews(rootView);
        setupRecyclerView();
        setupClickListeners();

        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadData(); // 开始加载数据
    }

    protected int getFragmentLayoutRes() {
        // 默认使用通用布局，子类可重写
        return R.layout.fragment_weather_forecast;
    }

    private void initViews(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        progressBar = rootView.findViewById(R.id.progressBar);
        errorTextView = rootView.findViewById(R.id.errorTextView);
        loadingLayout = rootView.findViewById(R.id.loadingLayout);
        errorLayout = rootView.findViewById(R.id.errorLayout);
        emptyLayout = rootView.findViewById(R.id.emptyLayout);
        retryButton = rootView.findViewById(R.id.retryButton);

        // 7天预报特殊组件初始化
        if (rootView.findViewById(R.id.tvAqi) != null) {
            initAqiView(rootView);
        }
    }

    protected void initAqiView(View rootView) {
        // 7天预报专属逻辑
        TextView tvAqi = rootView.findViewById(R.id.tvAqi);
        if (tvAqi != null) {
            tvAqi.setOnClickListener(v -> showAqiDetailDialog());
        }
    }

    private void setupRecyclerView() {
        adapter = new WeatherAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 添加分割线（使用主题中定义的divider）
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.divider));
        recyclerView.addItemDecoration(dividerItemDecoration);
    }

    private void setupClickListeners() {
        if (retryButton != null) {
            retryButton.setOnClickListener(v -> retryLoadData());
        } else if (errorLayout != null) {
            errorLayout.setOnClickListener(v -> retryLoadData());
        }
    }

    //================ 状态控制方法 ================//
    protected void showLoading() {
        Log.d(TAG, "Showing loading state");
        hideAllStates();
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.VISIBLE);
        }
        recyclerView.setVisibility(View.GONE);
    }

    protected void showData(List<WeatherData> data) {
        Log.d(TAG, "Showing data state with " + data.size() + " items");
        hideAllStates();
        recyclerView.setVisibility(View.VISIBLE);
        adapter.updateData(data);

        if (data.isEmpty()) {
            showEmpty();
        }
    }

    protected void showError(String message) {
        Log.e(TAG, "Showing error state: " + message);
        hideAllStates();
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
        if (errorTextView != null) {
            errorTextView.setText(message != null ? message : getString(R.string.default_error_message));
        }
    }

    protected void showEmpty() {
        Log.d(TAG, "Showing empty state");
        hideAllStates();
        if (emptyLayout != null) {
            emptyLayout.setVisibility(View.VISIBLE);
        }
    }

    private void hideAllStates() {
        if (loadingLayout != null) loadingLayout.setVisibility(View.GONE);
        if (errorLayout != null) errorLayout.setVisibility(View.GONE);
        if (emptyLayout != null) emptyLayout.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    //================ 抽象方法 ================//
    protected abstract void loadData();

    protected void retryLoadData() {
        if (retryCount < MAX_RETRY_COUNT) {
            retryCount++;
            Log.d(TAG, "Retrying data load. Retry count: " + retryCount);
            showLoading();
            loadData();
        } else {
            Log.e(TAG, "Max retry count reached.");
            showError("重试次数已达上限，请稍后再试。");
        }
    }

    //================ 7天预报专属方法 ================//
    protected void showAqiDetailDialog() {
        // 实现AQI详情弹窗
        FragmentActivity activity = getActivity();
        if (activity != null) {
            new AlertDialog.Builder(activity)
                    .setTitle("空气质量详情")
                    .setMessage("当前AQI指数：72\n等级：良好\n主要污染物：PM2.5")
                    .setPositiveButton("确定", null)
                    .show();
        }
    }

    protected void updateAqiView(int aqiValue) {
        if (getView() == null) return;

        TextView tvAqi = getView().findViewById(R.id.tvAqi);
        if (tvAqi != null) {
            tvAqi.setText("AQI: " + aqiValue);
            tvAqi.setBackgroundResource(getAqiBackground(aqiValue));
        }
    }

    private int getAqiBackground(int aqi) {
        if (aqi <= 50) return R.drawable.bg_aqi_good;
        else if (aqi <= 100) return R.drawable.bg_aqi_moderate;
        else return R.drawable.bg_aqi_unhealthy;
    }
}